package org.example.commons.service.impl;

import org.example.commons.entity.SysRole;
import org.example.commons.entity.SysUserRole;
import org.example.commons.repository.SysUserRoleRepository;
import org.example.commons.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * author 陈伯瑞
 * date 2020/6/16 0016 19:00
 * version 1.0
 **/
@Service
public class SysUserRoleServiceIml implements ISysUserRoleService {

    @Autowired
    SysUserRoleRepository sysUserRoleRepository;

    @Override
    public SysUserRole queryById(Long id) {
        return sysUserRoleRepository.getOne(id);
    }

    @Override
    public Page<SysUserRole> queryAllPage(Pageable pageable) {
        return sysUserRoleRepository.findAll(pageable);
    }

    @Override
    public List<SysUserRole> queryAll() {
        return sysUserRoleRepository.findAll();
    }

    @Override
    public SysUserRole insert(SysUserRole entity) {
        return sysUserRoleRepository.save(entity);
    }

    @Override
    public SysUserRole update(SysUserRole entity) {
        return sysUserRoleRepository.save(entity);
    }

    @Override
    public void deleteById(Long id) {
        sysUserRoleRepository.deleteById(id);
    }

    @Override
    public List<SysRole> findRoleByAdminId(Long adminId) {
        return sysUserRoleRepository.findRoleByAdminId(adminId);
    }

    @Override
    public List<Long> findRoleIdByAdminId(Long adminId) {
        return sysUserRoleRepository.findRoleIdByAdminId(adminId);
    }

    @Override
    public void updateRoleByAdminId(Long[] roles, Long adminId) {
        List<Long> originRoleIds = sysUserRoleRepository.findRoleIdByAdminId(adminId);
        //搜索要删除的角色
        for (Long originRoleId : originRoleIds) {
            boolean delFlag = true;
            for (Long role : roles) {
                if (role.equals(originRoleId)){
                    delFlag = false;
                    break;
                }
            }
            if (delFlag)
                sysUserRoleRepository.deleteByRoleId(originRoleId);
        }
        //搜索要增加的角色
        for (Long role : roles) {
            boolean addFlag = true;
            for (Long originRoleId : originRoleIds) {
                if (role.equals(originRoleId)){
                    addFlag = false;
                    break;
                }
            }
            if (addFlag){
                SysUserRole userRole = new SysUserRole();
                userRole.setAdminId(adminId);
                userRole.setRoleId(role);
                sysUserRoleRepository.save(userRole);
            }
        }
    }
}
